import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:live_music/components/ui/theme.dart';
import 'package:live_music/http/http_utils.dart';
import 'package:live_music/pages/agreement/privacy.dart';
import 'package:live_music/pages/agreement/user.dart';
import 'package:live_music/pages/login/forget.dart';
import 'package:live_music/services/userService.dart';
import 'package:live_music/utils/toast_utils.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key key}) : super(key: key);

  @override
  State<RegisterPage> createState() => _RegisterState();
}

class _RegisterState extends State<RegisterPage> {
  TextEditingController _pwdEditController;
  TextEditingController _userNameEditController;
  TextEditingController _codeditController;
  Timer _timer;
  int _countdownTime = 0;
  bool disabledPublish = true;
  @override
  void initState() {
    super.initState();

    _pwdEditController = TextEditingController();
    _userNameEditController = TextEditingController();
    _codeditController = TextEditingController();
    _pwdEditController.addListener(() => setState(() => {}));
    _userNameEditController.addListener(() => setState(() => {}));
  }

  String handleCodeAutoSizeText() {
    if (_countdownTime > 0) {
      return '($_countdownTime)s后重新发送';
    } else
      return '获取验证码';
  }

  startCountdown() {
    _countdownTime = 180;
    final call = (timer) {
      if (_countdownTime < 1) {
        _timer.cancel();
        _timer = null;
      } else {
        setState(() {
          _countdownTime -= 1;
        });
      }
    };
    if (_timer == null) {
      _timer = Timer.periodic(Duration(seconds: 1), call);
    }
  }

  sendCode() async {
    if (!validateUsername()) {
      return;
    }
    startCountdown();
    Map<String, dynamic> params = {
      "username": _userNameEditController.text,
    };
    await UserService.getMailCode(params)
        .then((value) => {ToastUtils.showToast("验证码已发送，注意查收!")})
        .catchError(
            (error) => {ToastUtils.showToast(error['retdesc']), _timer = null});
  }

  bool validateUsername() {
    String regexEmail =
        "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}\$";
    if (_userNameEditController.text == '') {
      ToastUtils.showToast("请输入邮箱或者手机号");
      return false;
    }
    if(_userNameEditController.text.contains('@')){
          if (!RegExp(regexEmail).hasMatch(_userNameEditController.text)) {
      ToastUtils.showToast("邮箱格式不正确");
      return false;
    }
    }else{
      String regexPhone="^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$";
          if (!RegExp(regexPhone).hasMatch(_userNameEditController.text)) {
      ToastUtils.showToast("手机号格式不正确");
      return false;
    }
    }
    return true;
  }
  bool validateLogin() {
    if (_pwdEditController.text == '') {
      ToastUtils.showToast("请输入密码");
      return false;
    }
    if (_pwdEditController.text.length < 6) {
      ToastUtils.showToast("密码不能小于6位!");
      return false;
    }
    if (_codeditController.text.length != 6) {
      ToastUtils.showToast("请输入6位验证码!");
      return false;
    }
    return true;
  }

  void loginBtnClicked() async {
    if (!validateLogin()) {
      return;
    }
    if (!validateUsername()) {
      return;
    }
    try {
      setState(() {
        disabledPublish = false;
      });
      EasyLoading.show(status: '注册中...');
      Map<String, dynamic> params = {
        "username": _userNameEditController.text,
        "password": _pwdEditController.text,
        "randomKey": "OQlRb3WW89yfycQb97Rrt1Ef2OprRyKp",
        "code": _codeditController.text,
        "name": '你的名字'
      };
      //你的名字
      await UserService.register(params)
          .then((value) => {ToastUtils.showToast("账号注册成功!"), Get.back()})
          .catchError((error) =>
              {ToastUtils.showToast(error['retdesc']), _timer = null});
      setState(() {
        disabledPublish = true;
      });
      EasyLoading.dismiss(animation: true);
    } catch (e) {
      setState(() {
        disabledPublish = true;
      });
      EasyLoading.showError('注册失败');
      EasyLoading.dismiss(animation: true);
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (_timer != null) {
      _timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: Container(
          alignment: Alignment.centerLeft,
          padding: const EdgeInsets.symmetric(horizontal: 26),
          margin: const EdgeInsets.only(bottom: 40),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              buildPhone(),
              buildVerifyCode(),
              buildPassWord(),
              loginButton(),
              Container(
                margin: const EdgeInsets.only(top: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Opacity(
                      opacity: 0,
                      child: Text(
                        "忘记密码?",
                        style: TextStyle(
                          color: WcaoTheme.placeholder,
                          fontSize: 12,
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        Get.back();
                      },
                      child: Container(
                        alignment: Alignment.center,
                        child: Text(
                          "登录",
                          style: TextStyle(
                            color: Colors.redAccent,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                    InkWell(
                      onTap: () {
                        Get.off(ForgetPage());
                      },
                      child: Text(
                        "找回密码?",
                        style: TextStyle(
                          color: WcaoTheme.secondary,
                          fontSize: 12,
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.only(top: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "登录即同意",
                      style: TextStyle(
                        color: WcaoTheme.secondary,
                      ),
                    ),
                    InkWell(
                      child: const Text('《用户协议》'),
                      onTap: () => Get.to(AgreementUser()),
                    ),
                    Text(
                      "及",
                      style: TextStyle(
                        color: WcaoTheme.secondary,
                      ),
                    ),
                    InkWell(
                      child: const Text('《隐私政策》'),
                      onTap: () => Get.to(AgreementPrivacy()),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Column buildPhone() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '注册',
          style: TextStyle(
            fontSize: 30,
            fontWeight: FontWeight.w500,
            color: WcaoTheme.base,
          ),
        ),
        Container(
          margin: const EdgeInsets.only(top: 36),
          child: Wrap(
            children: [
              Text(
                '邮箱或者手机号',
                style: TextStyle(
                  fontSize: 14,
                  color: WcaoTheme.secondary,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.only(top: 12),
          height: 50,
          child: TextField(
            controller: _userNameEditController,
            onChanged: (value) {
              print(value);
              setState(() {
                // checkLoginText();
              });
            },
            cursorColor: Colors.redAccent,
            decoration: InputDecoration(
              filled: true,
              fillColor: Colors.white,
              hintText: "请输入邮箱或者手机号",
              contentPadding:
                  const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20),
                borderSide: BorderSide(
                  color: WcaoTheme.outline,
                  width: 1,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20),
                borderSide: BorderSide(
                  color: WcaoTheme.outline,
                  width: 1,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 密码登录
  /// 密码登录
  Column buildPassWord() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: const EdgeInsets.only(top: 12),
          child: Wrap(
            children: [
              Text(
                '密码',
                style: TextStyle(
                  fontSize: 14,
                  color: WcaoTheme.secondary,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.only(top: 12),
          height: 50,
          child: TextField(
            controller: _pwdEditController,
            onChanged: (value) {
              setState(() {
                // checkLoginText();
              });
            },
            inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.allow(
                  RegExp("[a-zA-Z]|[!\"#\$%&'()*+,-./:;<=>?@^_`{|}~\\]|[0-9]")),
              LengthLimitingTextInputFormatter(10) //限制长度
            ],
            keyboardType: TextInputType.visiblePassword,
            obscureText: true,
            enableSuggestions: false,
            autocorrect: false,
            cursorColor: Colors.redAccent,
            decoration: InputDecoration(
              hintText: "请输入密码",
              contentPadding:
                  const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20),
                borderSide: BorderSide(
                  color: WcaoTheme.outline,
                  width: 1,
                ),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(20),
                borderSide: BorderSide(
                  color: WcaoTheme.outline,
                  width: 1,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 登录按钮
  loginButton() {
    return Container(
        margin: const EdgeInsets.only(top: 36),
        alignment: Alignment.center,
        width: double.infinity,
        height: 44,
        decoration: BoxDecoration(
          color: Colors.red[400],
          borderRadius: BorderRadius.circular(20),
        ),
        child: ElevatedButton(
            style: ButtonStyle(
                padding: MaterialStateProperty.all(EdgeInsets.zero),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20))),
                backgroundColor: MaterialStateProperty.all(
                  Colors.redAccent,
                )),
            onPressed: disabledPublish ? loginBtnClicked : null,
            child: const Center(
              child: Text(
                '注册',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.w500),
              ),
            )));
  }

  /// 验证码
  Column buildVerifyCode() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          margin: const EdgeInsets.only(top: 12),
          child: Wrap(
            children: [
              Text(
                '验证码',
                style: TextStyle(
                  fontSize: 14,
                  color: WcaoTheme.secondary,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
        Stack(
          children: [
            Container(
              margin: const EdgeInsets.only(top: 12),
              height: 50,
              child: TextField(
                controller: _codeditController,
                keyboardType: TextInputType.number,
                maxLines: 1,
                maxLength: 6,
                cursorColor: Colors.redAccent,
                decoration: InputDecoration(
                  counterText: "",
                  hintText: "输入验证码",
                  contentPadding:
                      const EdgeInsets.symmetric(vertical: 0, horizontal: 16),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20),
                    borderSide: BorderSide(
                      color: WcaoTheme.outline,
                      width: 1,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20),
                    borderSide: BorderSide(
                      color: WcaoTheme.outline,
                      width: 1,
                    ),
                  ),
                ),
              ),
            ),
            Positioned(
              right: 0,
              bottom: 0,
              child: InkWell(
                onTap: () {
                  if (_countdownTime == 0) {
                    sendCode();
                  }
                },
                child: Container(
                  padding: const EdgeInsets.only(right: 16),
                  alignment: Alignment.center,
                  height: 50,
                  child: Text(
                    handleCodeAutoSizeText(),
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.redAccent,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ],
    );
  }
}
